import os.path
from datetime import datetime

from django.contrib.auth.models import User
from django.db import IntegrityError
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views import View

from demo.form import ArticleForm
from demo.models import Classes, Article
from django_test.settings import MEDIA_ROOT
from user.form import UserForm


# Create your views here.
class UserViews(View):
    def get(self, request):
        return render(request, 'user/register.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST['password']
        print('用户名是：', username)
        print('密码是：', password)
        if not username:
            message = '注册失败,请输入用户名'
        elif len(username) < 2 or len(username) > 10:
            message = '注册失败，用户名长度为2-10'
        elif not password:
            message = '注册失败，请输入密码'
        elif len(password) < 6 or len(password) > 20:
            message = '注册失败，密码长度为6-20'
        else:
            user = User(username=username)
            user.set_password(password)
            try:
                user.save()
            except IntegrityError:
                message = '用户名已存在，请输入其他的用户名'
            else:
                message = '注册成功'
        return render(request, 'user/register.html', {'message': message, 'username': username})


class LoginView(View):
    def get(self, request):
        form = UserForm()
        return render(request, 'user/login.html', {'form': form})

    def post(self, request):
        # 获取用户输入的账号和密码
        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                message = '账号不存在'
            else:
                if user.check_password(password):
                    request.session['username'] = username  # 创建session信息，会话维持
                    # request.session.set_expriy(5000)  #设置会话过期时间
                    return redirect('index')
                else:
                    message = '密码错误'

        return render(request, 'user/login.html', {'message': message, 'form': form, 'username': username})


def logout(request, **kwargs):
    request.session.flush()
    return redirect('login')


class AddArticleView(View):
    # @method_decorator(login_required)
    def get(self, request):
        username = request.session.get('username')
        user = User.objects.get(username=username).id
        form = ArticleForm(request.FILES)
        if form.is_valid():
            title = form.cleaned_data['title']
            desc = form.cleaned_data['desc']
            content = form.cleaned_data['content']
            cover = form.cleaned_data['cover']
            classes = form.cleaned_data['classes']
            classes = Classes.objects.get(name=classes).id
            label = form.cleaned_data['label']
            Article.objects.create(
                user_id=user, classes_id=classes, title=title, desc=desc, content=content, cover=cover, label=label
            )
        return render(request, 'demo/add_article.html',
                      {'form': form,'username': username})

    # @method_decorator(login_required)
    def post(self, request):
        username = request.session.get('username')
        user = User.objects.get(username=username).id
        form = ArticleForm(request.POST,request.FILES)
        if form.is_valid():
            title = form.cleaned_data['title']
            desc = form.cleaned_data['desc']
            content = form.cleaned_data['content']
            cover = form.cleaned_data['cover']
            classes = form.cleaned_data['classes']
            label = form.cleaned_data['label']
            file_name=f'{datetime.now().strftime("%Y%m%d%H%M%S")}_{cover.name}'
            with open(os.path.join(MEDIA_ROOT,file_name),'wb') as fp:
                for data in cover.chunks():
                    fp.write(data)
            article=Article.objects.create(
                user=user, classes=classes, title=title, desc=desc, content=content, cover=cover
            )
            for i in label:
                article.label.add(i)
            print('成功发布')
        else:
            print('没有通过校验')
        return render(request, 'demo/add_article.html',
                      {'form': form,'username': username})
